<?php
/**
 * 编写者：Jayson
 * 编写日期：2024-06-13 09:25:29
 */

namespace App\Http\Controllers\wechat\applet;

use App\Http\Controllers\Controller;
use App\Models\users\UsersModel;
use App\Service\Authorization\LoginService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use lxs\aliyun\OssStorage;
use lxs\aliyun\SendSms;
use lxs\api\ApiResponse;
use lxs\tools\AuthToken;

class LoginController extends Controller {

    /**
     * 获取微信头像
     */
    public function getUserAvatar(): JsonResponse
    {
        $file = request()->file('file');
        $path = Request()->input('name');
        if ($path) {
            $path = 'tmui/' . $path;
        }
        if (!$file) {
            return ApiResponse::apiResponseData(101, "请上传头像");
        }
        $result = (new OssStorage())->Uploads($file, $path);
        if ($result) {
            return ApiResponse::apiResponseData(200, "上传成功", [
                'url' => $result,
            ]);
        }
        return ApiResponse::apiResponseData(102, "上传失败");
    }


    /**
     * 发送验证码
     */
    public function sendCaptcha(): JsonResponse
    {
        $mobile = request()->input('mobile');

        if (!$mobile) {
            return ApiResponse::apiResponseData(101, "请输入手机号码");
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return ApiResponse::apiResponseData(102, "手机号码格式不正确");
        }

        // 生成随机验证码
        $captcha = mt_rand(100000, 999999);

        Redis::setEx($mobile, 300, $captcha);

        $sendSms = new SendSms();
        $result = $sendSms->send($mobile, ['code' => $captcha], 'login_code');
        if ($result !== true) {
            return ApiResponse::apiResponseData(103, "发送失败");
        }

        return ApiResponse::apiResponseData(200, "验证码发送成功");
    }


    /**
     * 用户注册
     */
    public function register_submit(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'code' => ['required'],
            'mobile' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (!preg_match('/^1[3-9]\d{9}$/', $value)) {
                        $fail('手机号码格式不正确');
                    }
                    if (UsersModel::where('mobile', $value)->exists()) {
                        $fail('手机号码已存在');
                    }
                }
            ],
            'password' => ['required', 'min:6', 'max:20'],
            'password_form' => ['required', 'same:password'],
            'nickname' => ['required'],
            'captcha' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (Redis::get(request()->input('mobile')) != $value) {
                        $fail('验证码错误');
                    }
                }
            ],
        ], [
            'code.required' => '请稍后重试',
            'mobile.required' => '请输入手机号码',
            'mobile.mobile' => '请输入正确的手机号码',
            'password.required' => '请输入密码',
            'password.min' => '密码长度不能小于6位',
            'password.max' => '密码长度不能大于20位',
            'password_form.required' => '请输入确认密码',
            'password_form.same' => '两次密码不一致',
            'nickname.required' => '请输入昵称',
            'captcha.required' => '请输入验证码',
        ]);

        if ($validator->fails()) {
            return ApiResponse::apiResponseData(5006, $validator->errors()->first());
        }

        $validated = $request->only(['mobile', 'password', 'nickname', 'avatar', 'captcha', 'code']);

        $result = LoginService::instance()->registerSubmit($validated);
        if ($result['code'] == 200) {
            return ApiResponse::apiResponseData(200, $result['message']);
        }
        return ApiResponse::apiResponseData(5006, $result['message']);
    }


    /**
     * 密码登录提交
     */
    public function passwordLoginSubmit(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'code' => ['required'],
            'mobile' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (!preg_match('/^1[3-9]\d{9}$/', $value)) {
                        $fail('手机号码格式不正确');
                    }
                }
            ],
            'password' => ['required', 'min:6', 'max:20']
        ], [
            'code.required' => '请稍后重试',
            'mobile.required' => '请输入手机号码',
            'mobile.mobile' => '请输入正确的手机号码',
            'password.required' => '请输入密码',
            'password.min' => '密码长度不能小于6位',
            'password.max' => '密码长度不能大于20位',
        ]);

        if ($validator->fails()) {
            return ApiResponse::apiResponseData(5006, $validator->errors()->first());
        }

        $validated = $request->only(['mobile', 'password', 'code']);

        $result = LoginService::instance()->passwordLoginSubmit($validated['mobile'], $validated['password'], $validated['code'], 'wechat');

        if ($result['code'] == 200) {
            return ApiResponse::apiResponseData(200, '登录成功', [
                'token' => $result['data'],
            ]);
        }

        return ApiResponse::apiResponseData($result['code'], $result['message']);
    }


    /**
     * 用户登录
     */
    public function captchaLoginSubmit(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'code' => ['required'],
            'mobile' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (!preg_match('/^1[3-9]\d{9}$/', $value)) {
                        $fail('手机号码格式不正确');
                    }
                }
            ],
            'captcha' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (Redis::get(request()->input('mobile')) != $value) {
                        $fail('验证码错误');
                    }
                }
            ],
        ], [
            'code.required' => '请稍后重试',
            'mobile.required' => '请输入手机号码',
            'mobile.mobile' => '请输入正确的手机号码',
            'captcha.required' => '请输入验证码'
        ]);

        if ($validator->fails()) {
            return ApiResponse::apiResponseData(5006, $validator->errors()->first());
        }

        $validated = $request->only(['mobile', 'code']);

        $result = LoginService::instance()->captchaLoginSubmit($validated['mobile'], $validated['code']);

        if ($result['code'] == 200) {
            return ApiResponse::apiResponseData(200, '登录成功', [
                'token' => $result['data'],
            ]);
        }

        return ApiResponse::apiResponseData($result['code'], $result['message']);
    }


    /**
     * 忘记密码
     */
    public function forgetPassword(): JsonResponse
    {
        $mobile = request()->input('mobile');
        $password = request()->input('password');
        $captcha = request()->input('captcha');

        if (!$mobile) {
            return ApiResponse::apiResponseData(101, "请输入手机号码");
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return ApiResponse::apiResponseData(102, "手机号码格式不正确");
        }

        if (!$password) {
            return ApiResponse::apiResponseData(103, "请输入密码");
        }

        if (!$captcha) {
            return ApiResponse::apiResponseData(104, "请输入验证码");
        }

        if (Redis::get($mobile) != $captcha) {
            return ApiResponse::apiResponseData(105, "验证码不正确");
        }

        $user_list = UsersModel::where('mobile', $mobile)->first();
        if ($user_list) {
            $user_list->password = hash_hmac('sha256', $password, config('app.key'));
            $user_list->save();
            return ApiResponse::apiResponseData(200, "修改成功");
        } else {
            return ApiResponse::apiResponseData(106, "用户不存在");
        }
    }


    /**
     * 微信小程序退出登录
     */
    public function wechatLogout(): JsonResponse
    {
        $auth = new AuthToken();
        $auth->destroyToken();
        return ApiResponse::apiResponseData(200, '退出成功');
    }


}
